package ee.wm.ilmataat;

import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import ee.wm.ilmataat.R.raw;
import ee.wm.ilmataat.xml.WeatherXmlImporter;

public class Main extends Activity implements LocationListener {

	private LocationManager lm;
	private WeatherXmlImporter importer = new WeatherXmlImporter();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		InputStream ins = getResources().openRawResource(raw.coordinates);
	}

	@Override
	protected void onResume() {
		/*
		 * onResume is is always called after onStart, even if the app hasn't
		 * been paused
		 * 
		 * add location listener and request updates every 1000ms or 10m
		 */
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		/* GPS, as it turns out, consumes battery like crazy */
		lm.removeUpdates(this);
		super.onResume();
	}

	@Override
	protected void onStop() {
		finish();
		super.onStop();
	}

	@Override
	public void onLocationChanged(Location location) {
		if (location != null) {
			Log.d("Ilmataat", location.getLatitude() + "");
			Log.d("Ilmataat", location.getLongitude() + "");
			/**Toast.makeText(Main.this,
					location.getLatitude() + "" + location.getLongitude(),
					Toast.LENGTH_LONG).show();*/
		}
		Station station = LocationComparison.findClosestStation(location,
				importer.importStations(this.getBaseContext()));
		Log.d("Ilmataat ", station.getName());
		Toast.makeText(Main.this,
				station.getName() + ": " + station.getAirTemperature()+" kraadi",
				Toast.LENGTH_LONG).show();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
}